package edu.uic.keyoutcomestrackertool;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.text.ParseException;
import java.util.List;

import edu.uic.keyoutcomestrackertool.fragments.DatePickerFragment;
import edu.uic.kott.db.KottDataSource;
import edu.uic.kott.model.Instructor;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.DialogFragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class AddEditCourse extends FragmentActivity implements DatePickerFragment.DatePickerDialogListener{

	KottDataSource datasource;

	private static final int START_DATE_ID = 1;
	private static final int END_DATE_ID = 2;
	private static final String LOGTAG = "KOTT";
	protected static final int REQUEST_CODE = 103;

	private EditText courseNameEditText;
	private EditText startDateEditText;	
	private EditText endDateEditText;
	private TextView classDayTimeTextView;
	private TextView startTimeTextView;
	private TextView endTimeTextView;
	private Button addDayTimeButton;
	private EditText targetedWssEditText;
	private EditText classLocationEditText;
	private Spinner instructorSpinner;
	private Button addInstructorTaButton;
	private Spinner taSpinner;

	private String className;
	private String startDate;
	private String endDate;
	private String days;
	private String startTime;
	private String endTime;
	private String tWSS;
	private String classLocation;
	private int instructorId;
	private int taId;

	List<Instructor> instructorList;
	List<Instructor> taList;

	Bundle extras;

	private String option;				//to determine if the screen loaded to add new class or edit existing class 

	private boolean requiredFields;		//to make sure user has filled in all mandatory fields

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_edit_course);

		courseNameEditText = (EditText) findViewById(R.id.courseNameEditText);
		startDateEditText = (EditText) findViewById(R.id.dateFirstClassEditText);
		classDayTimeTextView = (TextView) findViewById(R.id.classDayTimeTextView);
		startTimeTextView = (TextView) findViewById(R.id.startTimeTextView);
		endTimeTextView = (TextView) findViewById(R.id.endTimeTextView);
		addDayTimeButton = (Button) findViewById(R.id.addDayTimeButton);
		addDayTimeButton.setOnClickListener(selectDayTimeListener);
		endDateEditText = (EditText) findViewById(R.id.dateLastClassEditText);
		targetedWssEditText = (EditText) findViewById(R.id.weeklyStyduSessionsEditText);		
		classLocationEditText = (EditText) findViewById(R.id.classLocationEditText);

		//default values
		className = "";
		startDate = "";
		endDate = "";
		days = "";
		startTime = "";
		endTime = "";				
		tWSS = "5";
		classLocation = "Not Available";
		instructorId = 0;
		taId = 0;

		option = "add";		//by default it is add new class

		extras = getIntent().getExtras();
		if (extras != null && extras.getString("option") == "update"){
			option = "update";
			//populate data

		}

		addInstructorTaButton = (Button) findViewById(R.id.addInstructorTaButton);
		addInstructorTaButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startActivity(new Intent(AddEditCourse.this, AddEditInstructor.class));				
			}
		});

		datasource = new KottDataSource(this);		

		instructorList = datasource.findAllByType("Instructor");
		instructorSpinner = (Spinner)findViewById(R.id.instructorSpinner);		
		ArrayAdapter<Instructor> instructorAdapter = new ArrayAdapter<Instructor>(this, android.R.layout.simple_spinner_item, instructorList);
		instructorSpinner.setAdapter(instructorAdapter);
		instructorSpinner.setOnItemSelectedListener(instructorListener);

		taList = datasource.findAllByType("Ta");
		taSpinner = (Spinner)findViewById(R.id.taSpinner);		
		ArrayAdapter<Instructor> taAdapter = new ArrayAdapter<Instructor>(this, android.R.layout.simple_spinner_item, taList);
		taSpinner.setAdapter(taAdapter);
		taSpinner.setOnItemSelectedListener(taListener);
	}

	public void InputStartDate(View v) {
		DialogFragment newFragment = DatePickerFragment.newInstance(START_DATE_ID);
		newFragment.show(getFragmentManager(), "datePicker");
	}

	public void InputEndDate(View v) {
		DialogFragment newFragment = DatePickerFragment.newInstance(END_DATE_ID);
		newFragment.show(getFragmentManager(), "datePicker");
	}

	@Override
	public void onDateSet(int id, DatePicker view, int year, int month, int day) {
		Log.i("DatePicker", "Date picker set from id " + id + "!");

		switch (id) {
		case 1:
			startDateEditText.setText(String.valueOf(month+1)+"/"+String.valueOf(day)+"/"+String.valueOf(year));
			break;

		case 2:
			endDateEditText.setText(String.valueOf(month+1)+"/"+String.valueOf(day)+"/"+String.valueOf(year));
			break;
		}		
		try {
			compareDate();
		} catch (ParseException e) {
			e.printStackTrace();
		}		 
	}

	@SuppressLint("SimpleDateFormat")
	public void compareDate() throws ParseException{

		if((startDateEditText.length() >0) && (endDateEditText.length() >0) ){

			Toast msg;
			String sDate = startDateEditText.getText().toString();
			String eDate = endDateEditText.getText().toString();		

			SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");

			Date startDate = sdf.parse(sDate);
			Date endDate =  sdf.parse(eDate);

			if(startDate.compareTo(endDate)>=0)
				msg = Toast.makeText(this, "INCORRECT", Toast.LENGTH_SHORT);
			else
				msg = Toast.makeText(this, "CORRECT", Toast.LENGTH_SHORT);

			msg.show();
		}
	}


	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menu_save, menu);		
		return true;
	}

	AdapterView.OnItemSelectedListener instructorListener = new AdapterView.OnItemSelectedListener() {
		@Override
		public void onItemSelected(AdapterView<?> parent, View view,
				int position, long id) {
			Instructor instructor = (Instructor) parent.getItemAtPosition(position);
			instructorId = (int) instructor.getInstructorId();
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			instructorId = 0;				
		}			
	};

	AdapterView.OnItemSelectedListener taListener = new AdapterView.OnItemSelectedListener() {
		@Override
		public void onItemSelected(AdapterView<?> parent, View view,
				int position, long id) {
			Instructor instructor = (Instructor) parent.getItemAtPosition(position);
			taId = (int) instructor.getInstructorId();
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			taId = 0;				
		}			
	};


	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		requiredFields = true;

		if(courseNameEditText.getText().toString().length() > 0)
			className = courseNameEditText.getText().toString();
		else requiredFields = false;

		if(startDateEditText.getText().toString().length() > 0)
			startDate = startDateEditText.getText().toString();
		else requiredFields = false;

		if(endDateEditText.getText().toString().length() > 0)
			endDate = endDateEditText.getText().toString();
		else requiredFields = false;

		if(classDayTimeTextView.getText().toString().length() > 0)
			days = classDayTimeTextView.getText().toString();
		else requiredFields = false;

		if(startTimeTextView.getText().toString().length() > 0)
			startTime = startTimeTextView.getText().toString();
		else requiredFields = false;

		if(endTimeTextView.getText().toString().length() > 0)
			endTime = endTimeTextView.getText().toString();
		else requiredFields = false;

		if(targetedWssEditText.getText().toString().length() > 0)
			tWSS = targetedWssEditText.getText().toString();
		else requiredFields = false;

		if(classLocationEditText.getText().toString().length() > 0)
			classLocation = classLocationEditText.getText().toString();

		Log.i(LOGTAG, "Instructor id: " + String.valueOf(instructorId));
		Log.i(LOGTAG, "TA id: " + String.valueOf(taId));

		if(requiredFields == true){
			Intent intent = new Intent(this, Courses.class);
			intent.putExtra("className", className);
			intent.putExtra("startDate", startDate);
			intent.putExtra("endDate", endDate);
			intent.putExtra("days", days);
			intent.putExtra("startTime", startTime);
			intent.putExtra("endTime", endTime);
			intent.putExtra("tWSS", tWSS);
			intent.putExtra("classLocation", classLocation);
			intent.putExtra("instructorId", String.valueOf(instructorId));
			intent.putExtra("taId", String.valueOf(taId));
			intent.putExtra("option", option);
			setResult(RESULT_OK, intent);
			finish();
		}
		else{

			AlertDialog.Builder builder = new AlertDialog.Builder(AddEditCourse.this);
			builder.setTitle(R.string.dialogTitle_requiredClassFields);	//set message title from string resource
			builder.setMessage(R.string.dialogMsg_requiredClassFields);//set message content
			builder.setPositiveButton("OK", null);		//ok button to dismiss the dialog box

			AlertDialog errorDialog = builder.create();
			errorDialog.show();
		}
		return super.onOptionsItemSelected(item);
	}

	private OnClickListener selectDayTimeListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			Intent intent = new Intent(AddEditCourse.this, DayTime.class);
			startActivityForResult(intent, REQUEST_CODE);
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {		
		super.onActivityResult(requestCode, resultCode, intent);

		if(requestCode == REQUEST_CODE && resultCode == RESULT_OK){
			days = intent.getStringExtra("days");
			startTime = intent.getStringExtra("startTime");
			endTime = intent.getStringExtra("endTime");

			Log.i(LOGTAG, days +" " + startTime + " " + endTime);

			classDayTimeTextView.setText(days);
			startTimeTextView.setText(startTime);
			endTimeTextView.setText(endTime);}
	}
}
